import Vue from 'vue'
import VueRouter from 'vue-router'
import HeaderLayout from "@/views/common/HeaderLayout"
import NavLayout from "@/views/common/NavLayout"

const RouteView = {
    name: 'RouteView',
    render: h => h('router-view')
};

import routeData from "./route.json"

Vue.use(VueRouter)

// 处理动态引入组件函数
const getComponent = (data) => {
    data.map((item) => {
        const name = item.component
        if (name) {
            switch (name) {
                case 'HeaderLayout':
                    item.component = HeaderLayout
                    break
                case 'NavLayout':
                    item.component = NavLayout
                    break
                case 'RouteView':
                    item.component = RouteView
                    break
                default: {
                    item.component = () => import('@/views/' + name + '.vue')
                }
            }
            // 利用递归，处理多级路由
            if (item.children && item.children.length) {
                getComponent(item.children)
            }
        }
    })
    return data
}

let routes = getComponent(routeData)
console.log("routes", routes)
const router = new VueRouter({
    routes
})

// 获取原型对象push函数
const originalPush = VueRouter.prototype.push

// 获取原型对象replace函数
const originalReplace = VueRouter.prototype.replace

// 修改原型对象中的push函数
VueRouter.prototype.push = function push(location) {
    return originalPush.call(this, location).catch(err => err)
}

// 修改原型对象中的replace函数
VueRouter.prototype.replace = function replace(location) {
    return originalReplace.call(this, location).catch(err => err)
}


export default router
